package NC3_链表中环的入口结点;


class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}

public class Solution {

    public ListNode EntryNodeOfLoop(ListNode pHead) {
        if (pHead == null || pHead.next == null){
            return null;
        }

        ListNode fast = pHead;
        ListNode slow = pHead;
        while (fast != null){
            fast = fast.next.next;
            slow = slow.next;

            if (fast == slow){
                // 有环
                ListNode ringNode = foundNode(pHead, fast);
                return ringNode;
            }
        }
        return null;
    }

    private ListNode foundNode(ListNode p1, ListNode p2) {
        while (p1 != p2){
            p1 = p1.next;
            p2 = p2.next;
        }
        return p1;
    }
}